package com.tanhua.service;

import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.CommentVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.util.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentsService {
    @Reference
    private CommentApi commentApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private PublishApi publishApi;

    @Autowired
    private MovementMQService movementMQService;

    public ResponseEntity findComments(String movementId, Integer page, Integer pagesize) {
        PageResult pageResult = commentApi.findComments(movementId,page,pagesize);
        List<Comment> items = pageResult.getItems();
        ArrayList<CommentVO> vos = new ArrayList<>();
        for (Comment comment : items) {
            CommentVO commentVO = new CommentVO();
            BeanUtils.copyProperties(comment,commentVO);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(comment.getCreated()));
            commentVO.setCreateDate(format);
            commentVO.setId(comment.getId().toHexString());
            commentVO.setHasLiked(0);
            UserInfo userInfo = userInfoApi.findUserInfo(comment.getUserId());
            BeanUtils.copyProperties(userInfo,commentVO);
            vos.add(commentVO);
        }
        pageResult.setItems(vos);
        return ResponseEntity.ok(pageResult);
    }


    /**
     * 发表评论
     * @param publishId
     * @param content
     * @return
     */
    public ResponseEntity submitComment(String publishId, String content) {
        User user = UserHolder.getUser();
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setPubType(1);
        comment.setCommentType(2);
        comment.setContent(content);
        comment.setUserId(user.getId());
        Publish publish = publishApi.findById(publishId);
        comment.setPublishUserId(publish.getUserId());
        commentApi.save(comment);
        //发送消息
        movementMQService.sendUnlikePublishMsg(publishId);
        movementMQService.sendCommentPublishMsg(publishId);
        return ResponseEntity.ok(null);
    }
}
